#!/usr/bin/env python
# -*- coding: utf-8 -*-
# time: 2022/11/15 12:50
# file: captcha.py
# author: lotus163
import kaptcha

from ...core.custom_exc import LoginException
from ...core.redis import MyRedis, get_config_key, get_captcha_codes_key
from ...utils.string_util import string_to_bool, get_uuid


class CaptchaService:

    def __init__(self, redis: MyRedis):
        self.redis = redis

    async def is_captcha_enabled(self) -> bool:
        """是否开启验证码"""
        captcha_enabled_str = await self.redis.get(get_config_key("sys.account.captchaEnabled"))
        if captcha_enabled_str is not None:
            return string_to_bool(captcha_enabled_str)
        # 没有返回默认值True
        else:
            return True

    async def save_captcha_code(self, uuid, code):
        """保存验证码"""
        captcha_codes_key = get_captcha_codes_key(uuid)
        # 过期时间3分钟
        await self.redis.set(captcha_codes_key, code, ex=3 * 60)

    async def validate_captcha(self, uuid: str, captcha_code: str):
        """验证码验证"""
        # 获取验证码的key
        captcha_codes_key = get_captcha_codes_key(uuid)
        # 从redis获取code
        code = await self.redis.get(captcha_codes_key)
        if code is None:
            raise LoginException("验证码失效")
        # 必须在这个位置
        await self.redis.delete(captcha_codes_key)
        if code != captcha_code:
            raise LoginException("验证码错误")

    async def get_uuid_img(self):
        """获取uuid和img的base64"""
        code, image = kaptcha.Captcha().digit()
        img = image.split(",")[-1]
        uuid = get_uuid()
        # 保存到redis
        await self.save_captcha_code(uuid, code)
        return uuid, code, img
